packageLoad <-
function(x) {
for (i in 1:length(x)) {
if (!x[i] %in% installed.packages()) {
install.packages(x[i])
}
library(x[i], character.only = TRUE)
}
}Day 1
Set up an R Project
As a first step whenever you start a new project, workflow, analysis, etc., it is good practice to set up an R project. R Projects are RStudio’s way of bundling together all your files for a specific project, such as data, scripts, results, figures. Your project directory also becomes your working directory, so everything is self-contained and easily portable.
You can start an R project in an existing directory or in a new one. To create a project go to File -> New Project:

Let’s create a new directory and call it ‘R-for-Geospatial’. You can make it a sub directory of any folder you wish.

Now we are working in our R project. You can see the working directory printed at the top of your console is now our project directory, and in the ‘Files’ tab in RStudio you can see we have an .Rproj file, which will open up this R project in RStudio whenever you come back to it. For example close out of this R session, navigate to the project folder on your computer, and double-click the .Rproj file.
Read in R packages
Now we have started a fresh R session in our new R project, we need to read in the libraries needed to work through today’s lesson. You should have all packages installed after finished the set-up instructions on the Getting Started page.
In the set-up lesson, you used the following function to check if a package is installed, if not install it, and then load that package into your session.
We will be using this function the rest of the workshop to read in a list of packages at the beginning of each lesson, so lets store it as its own R script that we can call in later with the source() function. Sourcing functions is good practice as it reduces repetitiveness of rewriting them every time you want to use it.
Now let’s use it to load in our libraries needed for today. Assuming you already installed all of these, loading them should run pretty quick.
packageLoad(c("rgbif", "tidycensus", "tigris", "sf", "terra", "dplyr", "tidyr", "readr"))Today we are going to walk through how to import spatial data directly into R, clean it and save it so we can work with it the rest of the workshop. However, there are some data sets we will be using that are not covered in today’s lesson so you will need to download the data to use for Days 2 and 3. Click the download button below, and this will download a zipped folder called ‘course-data’. Next, extract all files from the folder, navigating to your project directory. This will then place a folder called ‘data’ within your project directory with all the data files you need for this workshop.